package com.haibei.activity.market;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.common.net.NetResult;
import com.common.task.BaseTask;
import com.common.task.NetCallBack;
import com.common.uitl.ListUtiles;
import com.common.uitl.LogUtil;
import com.common.uitl.StringUtils;
import com.common.uitl.Tool;
import com.haibei.App;
import com.haibei.R;
import com.haibei.activity.BaseHaibeiActivity;
import com.haibei.activity.SearchGoodsActivity;
import com.haibei.adapter.ExpandListSiftAdapter;
import com.haibei.adapter.ExpandListSiftAdapter.OnSelectChangeListener;
import com.haibei.adapter.ExpandListSiftAdapter.SiftBean;
import com.haibei.adapter.GoodsAdapter;
import com.haibei.adapter.SortAdapter;
import com.haibei.adapter.bean.BrandRegion;
import com.haibei.adapter.bean.Goods;
import com.haibei.adapter.bean.GoodsType;
import com.haibei.adapter.bean.SortBean;
import com.haibei.net.NetInterface;
import com.haibei.view.PullToRefreshView;
import com.haibei.view.PullToRefreshView.OnFooterRefreshListener;
import com.haibei.view.PullToRefreshView.OnHeaderRefreshListener;

public class MarketGoodsListActivity extends BaseHaibeiActivity implements OnHeaderRefreshListener, OnFooterRefreshListener,
		OnClickListener {

	private PullToRefreshView mPullToRefreshView;
	private ListView listViewGoodsList;
	private GoodsAdapter mAdapter = null;
	private ArrayList<Goods> mArrayListGoods;
	private final int page_size = 10;
	private final int INT_RTYPE_FIRST = 1;
	private final int INT_RTYPE_REFRESH = 2;
	private final int INT_RTYPE_LODMORE = 3;
	private View mPopupwindowViewSift = null;
	private View mPopupwindowViewSort = null;
	private PopupWindow mPhonePop = null;
	private static ArrayList<BrandRegion> mArrayListBrands;
	private static ArrayList<BrandRegion> mArrayLocation;
	private Button mButtonSort;
	private BaseTask mBaseTask;
	private ArrayList<SiftBean> mArrayListSiftBeans;
	private GoodsType mGoodsType;
	private HashMap<String, String> mHashMapParamMapSift;
	private HashMap<String, String> mHashMapParamMapSort;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mArrayListGoods = new ArrayList<Goods>();
		mArrayListSiftBeans = new ArrayList<ExpandListSiftAdapter.SiftBean>();
		mGoodsType = (GoodsType) getIntent().getSerializableExtra("goodsType");
		mHashMapParamMapSift = new HashMap<String, String>();
		mHashMapParamMapSort = new HashMap<String, String>();
		initView();
	}

	@Override
	public void initView() {
		setContentView(R.layout.activity_goods_list);
		listViewGoodsList = findListViewById(R.id.listViewGoodsList);
		mPullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);

		// mArrayListGoods.addAll(getGoodsList());
		// buildAdapter(getGoodsList(), INT_RTYPE_FIRST);

		findButtonById(R.id.buttonSift).setOnClickListener(this);
		findButtonById(R.id.buttonBack).setOnClickListener(this);
		findButtonById(R.id.buttonSort).setOnClickListener(this);
		// creatPhonePop();
		// 获取品牌以及产地
		getLocations();
		getBrands();
		if (ListUtiles.isEmpty(mArrayListGoods)) {
			requestData(INT_RTYPE_FIRST, mArrayListGoods.size());
		}
		findViewById(R.id.relativeLayoutSearch).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 搜索商品
				Tool.startActivity(MarketGoodsListActivity.this, SearchGoodsActivity.class);
			}
		});
	}

	private void requestData(int type, int offset) {
		// categoryParId = 一级类目ID， categorySubId=二级类目ID，
		// brandId=牌品ID，regionId=产地ID，
		// promotion=是否是促销：boolean类型， orderBy = 做商品展示排序所用：1 = 价格升序，2=价格降序，
		// 3=上架时间降序，4=销量降序;

		HashMap<String, String> hmap = new HashMap<String, String>();
		hmap.put("offset", String.valueOf(offset));
		hmap.put("limit", String.valueOf(page_size));
		if (null != mGoodsType) {
			hmap.put("categoryParId", mGoodsType.getId());
		}
		// 筛选条件
		for (Entry<String, String> entry : mHashMapParamMapSift.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			if (!StringUtils.isEmpty(value)) {
				hmap.put(key, value);
			}
		}
		// 排序条件
		for (Entry<String, String> entry : mHashMapParamMapSort.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			if (!StringUtils.isEmpty(value)) {
				hmap.put(key, value);
			}
		}
		getRequestTask(type).execute(hmap);
	}

	private BaseTask getRequestTask(final int type) {
		if (null != mBaseTask && !mBaseTask.isCancelled()) {
			mBaseTask.cancel(true);
		}
		mBaseTask = new BaseTask(new NetCallBack() {

			@Override
			public void onPreCall() {
				if (INT_RTYPE_FIRST == type) {
					showProgressDialogWithTask(mBaseTask);
				}
			}

			@Override
			public void onFinish(NetResult result) {
				if (INT_RTYPE_FIRST == type) {
					hideProgressDialogWithTask();
				}
				if (null != result) {
					if (result.isSuccess()) {
						ArrayList<Goods> list = (ArrayList<Goods>) (result.getData()[0]);
						buildAdapter(list, type);
					} else {
						Tool.ToastShow(MarketGoodsListActivity.this, result.getMessage());
					}
				} else {
					Tool.ToastShow(MarketGoodsListActivity.this, R.string.error_net);
				}
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult result = null;
				try {
					result = NetInterface.listGoods(MarketGoodsListActivity.this, paramMap);
				} catch (Exception e) {
				}
				return result;
			}
		});
		return mBaseTask;
	}

	private void createSiftPop(ArrayList<SiftBean> siftList) {
		/* create pop-up window */
		if (null == mPopupwindowViewSift) {
			LayoutInflater layout_infalter = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
			mPopupwindowViewSift = layout_infalter.inflate(R.layout.pop_sift_view, null);
		}

		final ExpandListSiftAdapter elsAda = new ExpandListSiftAdapter(this, siftList);
		final ExpandableListView expandLabel = (ExpandableListView) mPopupwindowViewSift.findViewById(R.id.expanedListSiftso);
		expandLabel.setAdapter(elsAda);
		expandLabel.setOnGroupExpandListener(new OnGroupExpandListener() {
			@Override
			public void onGroupExpand(int groupPosition) {
				elsAda.expands(String.valueOf(groupPosition));
			}
		});
		expandLabel.setOnGroupCollapseListener(new OnGroupCollapseListener() {
			@Override
			public void onGroupCollapse(int groupPosition) {
				elsAda.expands(String.valueOf(groupPosition));
			}
		});

		Button btnCanCell = (Button) mPopupwindowViewSift.findViewById(R.id.buttonCancell);
		Button btnCanConfirm = (Button) mPopupwindowViewSift.findViewById(R.id.buttonConfirm);
		mPhonePop = new PopupWindow(mPopupwindowViewSift, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		mPhonePop.setAnimationStyle(R.style.golf_phone_popup);
		mPhonePop.update();
		btnCanCell.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {// 关闭popWindow
				if (true == mPhonePop.isShowing()) {
					mPhonePop.dismiss();
				}
			}
		});
		btnCanConfirm.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (true == mPhonePop.isShowing()) {// 确定用户的筛选条件并执行筛选
					mPhonePop.dismiss();// // brandId=牌品ID，regionId=产地ID，
					HashSet<SiftBean> selectSets = elsAda.getSelect();
					for (SiftBean sb : selectSets) {
						mHashMapParamMapSift.put(sb.getParamKey(), sb.getSiftValue());
					}
					// ==========
					requestData(INT_RTYPE_REFRESH, 0);// 参数在requestData中组合
				}
			}
		});
		final View viewAll = mPopupwindowViewSift.findViewById(R.id.relayoutLayoutAll);
		final ImageView imageViewAllHook = (ImageView) mPopupwindowViewSift.findViewById(R.id.imageViewHookSub);
		viewAll.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (null == viewAll.getTag()) {// 是否选择全部的标记
					viewAll.setTag(new Object());
					imageViewAllHook.setImageResource(R.drawable.bg_radio_check);
					mHashMapParamMapSift.clear();// 清除已经选择的条件，所有已经选择
					elsAda.clearSelect();// 清除筛选条件
				} else {
					viewAll.setTag(null);
					imageViewAllHook.setImageResource(R.drawable.bg_radio_uncheck);
				}
			}
		});
		elsAda.setOnSelectChangeListener(new OnSelectChangeListener() {// 清除全部选择字样
			@Override
			public void OnSelectChange(HashSet<SiftBean> siftBeans) {
				viewAll.setTag(null);
				imageViewAllHook.setImageResource(R.drawable.bg_radio_uncheck);
			}
		});
	}

	private void createSortPop() {
		if (null == mPopupwindowViewSort) {
			LayoutInflater layout_infalter = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
			mPopupwindowViewSort = layout_infalter.inflate(R.layout.pop_sort_view, null);
		}
		final ListView listViewSort = (ListView) mPopupwindowViewSort.findViewById(R.id.listViewSort);

		ArrayList<SortBean> sortBeans = new ArrayList<SortBean>();
		// 默认，价格，时间，销量，1 = 价格升序，2=价格降序， 3=上架时间降序，4=销量降序;
		sortBeans.add(new SortBean("默认", ""));

		sortBeans.add(new SortBean("价格升序", "1"));
		sortBeans.add(new SortBean("价格降序", "2"));
		sortBeans.add(new SortBean("上架时间", "3"));
		sortBeans.add(new SortBean("销量降序", "4"));

		final SortAdapter sortAda = new SortAdapter(this, sortBeans);
		listViewSort.setAdapter(sortAda);
		listViewSort.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				try {
					SortBean sortBean = (SortBean) parent.getItemAtPosition(position);
					sortAda.setIndex(position);
					mPopupwindowViewSort.setTag(sortBean);

				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});
		// ==========
		Button btnCanCell = (Button) mPopupwindowViewSort.findViewById(R.id.buttonCancell);
		Button btnCanConfirm = (Button) mPopupwindowViewSort.findViewById(R.id.buttonConfirm);
		mPhonePop = new PopupWindow(mPopupwindowViewSort, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		mPhonePop.setAnimationStyle(R.style.golf_phone_popup);
		mPhonePop.update();
		btnCanCell.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (true == mPhonePop.isShowing()) {
					mPhonePop.dismiss();
				}
			}
		});
		btnCanConfirm.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (true == mPhonePop.isShowing()) {
					mPhonePop.dismiss();
					// 商品搜索接口
					Object sortObj = mPopupwindowViewSort.getTag();
					if (null != sortObj) {
						SortBean sorB = (SortBean) sortObj;
						mHashMapParamMapSort.put("orderBy", sorB.getValue());
					}
					requestData(INT_RTYPE_REFRESH, 0);// 参数在requestData中组合
				}
			}
		});
	}

	private void buildAdapter(ArrayList<Goods> godsList, int type) {

		switch (type) {
		case INT_RTYPE_FIRST:
			// 首次请求
			mArrayListGoods.clear();// 数据清零
			mArrayListGoods.addAll(godsList);
			mAdapter = new GoodsAdapter(this, mArrayListGoods);
			listViewGoodsList.setAdapter(mAdapter);
			break;
		case INT_RTYPE_REFRESH:
			mArrayListGoods.clear();// 数据清零
			mArrayListGoods.addAll(godsList);
			mAdapter.notifyDataSetChanged();
			break;
		case INT_RTYPE_LODMORE:
			mArrayListGoods.addAll(godsList);
			mAdapter.notifyDataSetChanged();
			break;
		}
		LogUtil.i(App.tag, "商品数:" + listViewGoodsList.getAdapter().getCount());
		listViewGoodsList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				try {
					Goods goods = (Goods) listViewGoodsList.getAdapter().getItem(position);
					LogUtil.i(App.tag, "商品Id：" + goods.getId());
					gotoDetail(goods);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	private void gotoDetail(Goods gods) {
		Intent intent = new Intent();
		intent.putExtra("goods", gods);
		intent.setClass(MarketGoodsListActivity.this, GoodsDetailActivity.class);
		startActivity(intent);
	}

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				LogUtil.i(App.tag, "onFooterRefresh");
				requestData(INT_RTYPE_LODMORE, mArrayListGoods.size());
				mPullToRefreshView.onFooterRefreshComplete();
			}
		}, 1000);
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				// 设置更新时间
				LogUtil.i(App.tag, "onHeaderRefresh");
				// mPullToRefreshView.onHeaderRefreshComplete("最近更新:01-23 12:01");
				requestData(INT_RTYPE_LODMORE, 0);
				mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1000);

	}

	

	@Override
	public void onClick(View v) {
		int vid = v.getId();
		switch (vid) {
		case R.id.buttonSort: {
			createSortPop();
			mPhonePop.setFocusable(true);
			mPhonePop.showAtLocation(findViewById(R.id.relativeLayoutBottom), Gravity.RIGHT | Gravity.BOTTOM, 0, 0);
		}
			break;
		case R.id.buttonBack:
			finish();
			break;
		case R.id.buttonSift: {
			// 弹出，筛选
			if (!ListUtiles.isEmpty(mArrayListBrands) && !ListUtiles.isEmpty(mArrayLocation)) {
				if (mArrayListSiftBeans.isEmpty()) {
					SiftBean sbLocation = new SiftBean();
					sbLocation.setSiftString("产地");
					// regionId=产地ID，
					for (BrandRegion location : mArrayLocation) {
						SiftBean sbtempLocation = new SiftBean();
						sbtempLocation.setSiftString(location.getName());
						sbtempLocation.setParamKey("regionId");
						sbtempLocation.setSiftValue(location.getId());
						sbLocation.addSiftBean(sbtempLocation);
					}
					mArrayListSiftBeans.add(sbLocation);

					SiftBean sbBrand = new SiftBean();
					sbBrand.setSiftString("品牌");
					for (BrandRegion brand : mArrayListBrands) {
						// brandId=牌品ID，
						SiftBean sbtempBrand = new SiftBean();
						sbtempBrand.setSiftString(brand.getName());
						sbtempBrand.setSiftValue(brand.getId());
						sbtempBrand.setParamKey("brandId");
						sbBrand.addSiftBean(sbtempBrand);
					}
					mArrayListSiftBeans.add(sbBrand);
				}
				createSiftPop(mArrayListSiftBeans);
				mPhonePop.setFocusable(true);
				mPhonePop.showAtLocation(findViewById(R.id.relativeLayoutBottom), Gravity.RIGHT | Gravity.BOTTOM, 0, 0);
			} else {
				if (ListUtiles.isEmpty(mArrayListBrands)) {
					getBrands();
				}
				if (ListUtiles.isEmpty(mArrayLocation)) {
					getLocations();
				}
			}

		}
			break;
		}
	}

	private void getBrands() {
		if (ListUtiles.isEmpty(mArrayListBrands)) {
			BaseTask btask = new BaseTask(new NetCallBack() {
				@Override
				public void onFinish(NetResult result) {
					if (null != result && result.isSuccess()) {
						mArrayListBrands = (ArrayList<BrandRegion>) result.getData()[0];
					}
				}

				@Override
				public NetResult onDoInBack(HashMap<String, String> paramMap) {
					NetResult netResult = null;
					try {
						netResult = NetInterface.listBrand(MarketGoodsListActivity.this, paramMap);
					} catch (Exception e) {
						e.printStackTrace();
					}
					return netResult;
				}
			});
			btask.execute(new HashMap<String, String>());
		}
	}

	private void getLocations() {
		if (ListUtiles.isEmpty(mArrayLocation)) {
			BaseTask btask = new BaseTask(new NetCallBack() {
				@Override
				public void onFinish(NetResult result) {
					if (null != result && result.isSuccess()) {
						mArrayLocation = (ArrayList<BrandRegion>) result.getData()[0];
					}
				}

				@Override
				public NetResult onDoInBack(HashMap<String, String> paramMap) {
					NetResult netResult = null;
					try {
						netResult = NetInterface.listRegion(MarketGoodsListActivity.this, paramMap);
					} catch (Exception e) {
						e.printStackTrace();
					}
					return netResult;
				}
			});
			btask.execute(new HashMap<String, String>());
		}

	}
}
